package com.dazzle.cameralib;

import android.app.Service;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.dazzle.cameralib.utils.DebugUtils;



/**
 * Created by gavin on 2016/11/23.
 */

class FloatPreviewWindow {

    public static final String TAG = "FloatPreviewWindow";
    //定义浮动窗口布局
    LinearLayout mFloatLayout;
    WindowManager.LayoutParams wmParams;
    //创建浮动窗口设置布局参数的对象
    WindowManager mWindowManager;

//    Button mFloatView;
    CameraTextureView mCameraTextureView;
    private Context mContext;
    private Service service;
    private Rect mRect;

    private static final int HIDE_FLOAT_VIEW = 1;
    private static final int SHOW_FLOAT_VIEW = 2;
    private static final int UPDATE_FLOAT_WINDOW = 3;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HIDE_FLOAT_VIEW:
                    DebugUtils.LogD(TAG, "HIDE_FLOAT_VIEW");
                    doHideFloatView();
                    break;
                case SHOW_FLOAT_VIEW:
                    DebugUtils.LogD(TAG, "SHOW_FLOAT_VIEW");
                    doShowFloatView();
                    break;
                case UPDATE_FLOAT_WINDOW:
                    doSetFloatViewRect((Rect)msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public CameraTextureView getCameraTextureView() {
        return mCameraTextureView;
    }


    public FloatPreviewWindow(Context context,  Rect rect) {
        mContext = context;
        service = (Service)context;
        mRect = rect;
    }

    public void createFloatView()
    {
        wmParams = new WindowManager.LayoutParams();
        //获取WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager)service.getApplication().getSystemService(service.getApplication().WINDOW_SERVICE);
        //设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags =
//          WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                  WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//          | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
        ;

        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;

        // 以屏幕左上角为原点，设置x、y初始值
        wmParams.x = mRect.left;
        wmParams.y = mRect.top;
        // 设置悬浮窗口长宽数据
        wmParams.width = mRect.width();
        wmParams.height = mRect.height();

        LayoutInflater inflater = LayoutInflater.from(service.getApplication());
        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.float_texture_view, null);
        mWindowManager.addView(mFloatLayout, wmParams);
        //浮动窗口按钮
        mCameraTextureView = (CameraTextureView)mFloatLayout.findViewById(R.id.float_texture);

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        doSetFloatViewRect(mRect);

        //设置监听浮动窗口的触摸移动
        mCameraTextureView.setOnTouchListener(new View.OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
                wmParams.x = (int) event.getRawX() - mCameraTextureView.getMeasuredWidth()/2;
                wmParams.y = (int) event.getRawY() - mCameraTextureView.getMeasuredHeight()/2;
                mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                return false;
            }
        });


        mCameraTextureView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
//                Toast.makeText(service, "onClick", Toast.LENGTH_SHORT).show();
                DebugUtils.LogE(TAG, "click windows");
            }
        });
    }

    public void setFloatViewRect(Rect rect) {
        Message msg = new Message();
        msg.what = UPDATE_FLOAT_WINDOW;
        msg.obj  = rect;
        handler.sendMessage(msg);
    }

    private void doSetFloatViewRect(Rect rect) {
        mRect = rect;
        DebugUtils.LogD(TAG, "doUpdateTextureViewSize");
        try {
            wmParams.x      = mRect.left;
            wmParams.y      = mRect.top;
            wmParams.width  = mRect.width();
            wmParams.height = mRect.height();
            mWindowManager.updateViewLayout(mFloatLayout, wmParams);
            mCameraTextureView.setLayoutParams(new LinearLayout.LayoutParams(mRect.width(), mRect.height()));
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    public void removeWindow() {
        if (mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
            mCameraTextureView = null;
        }
    }

    public void hideFloatView() {
        handler.sendEmptyMessage(HIDE_FLOAT_VIEW);
    }

    private void doHideFloatView() {
        if (mCameraTextureView != null) {
            mCameraTextureView.setVisibility(View.INVISIBLE);
            wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            mWindowManager.updateViewLayout(mFloatLayout, wmParams);
        }

    }

    private  void doShowFloatView() {
        if (mCameraTextureView != null) {
            mCameraTextureView.setVisibility(View.INVISIBLE);
            wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            mWindowManager.updateViewLayout(mFloatLayout, wmParams);
        }
    }

    public void showFloatView() {
        handler.sendEmptyMessage(SHOW_FLOAT_VIEW);
    }


}
